<style lang="less">
    @import "../../../../styles/common.less";
</style>

<template>
    <div>
        <Card dis-hover :bordered="false">
            <Row :gutter="16">
                <Col span="6">
                    <Card dis-hover>
                        <p slot="title">部门操作</p>
                        <Row>
                            <Form inline>
                                <FormItem>
                                    <Button type="primary" icon="plus-round" v-has="'dept:add'" @click="handleAddDept(1)">添加</Button>
                                    <Button type="success" icon="edit" v-has="'dept:update'" @click="handleAddDept(2)">编辑</Button>
                                    <Poptip confirm
                                            v-has="'dept:del'"
                                            title="您确认要删除选中的记录么？"
                                            @on-ok="handleDelDept"
                                            ok-text="确认"
                                            placement="right-start"
                                            cancel-text="取消">
                                        <Button type="error" icon="android-remove" >删除</Button>
                                    </Poptip>
                                </FormItem>
                            </Form>
                        </Row>
                        <Row>
                            <Tree :data="deptData"
                                  @on-select-change="handleselectchange"></Tree>
                        </Row>
                    </Card>
                </Col>
                <Col span="18">
                    <Card dis-hover>
                        <p slot="title">人员操作</p>
                        <Row>
                            <Form inline>
                                <FormItem>
                                    <Input v-model="realName" icon="ios-search-strong" placeholder="输入姓名过滤" @keydown.enter="handleSearch" @on-click="handleSearch">
                                    </Input>
                                </FormItem>
                                <FormItem>
                                    <Button type="primary" icon="plus-round" @click="handleAddMember(1)">添加</Button>
                                    <Button type="success" icon="edit" @click="handleAddMember(2)">编辑</Button>
                                    <Poptip confirm
                                            title="您确认要删除选中的记录么？"
                                            @on-ok="handleDelMember"
                                            ok-text="确认"
                                            placement="right-start"
                                            cancel-text="取消">
                                        <Button type="error" icon="android-remove" >删除</Button>
                                    </Poptip>
                                </FormItem>
                            </Form>
                        </Row>
                        <Row>
                            <Table border
                                   highlight-row
                                   ref="currentRowTable"
                                   :columns="DataColumns"
                                   :data="tableData"
                                   @on-current-change="handleRowChange"></Table>
                            <Page :total="dataCount"
                                  :page-size="pageSize"
                                  :show-total="true"
                                  class-name="comPage"
                                  show-sizer
                                  @on-change="changePage"></Page>
                        </Row>
                    </Card>
                </Col>
            </Row>
        </Card>
        <Modal
                title="部门数据"
                v-model="addDept"
                ok-text="保存"
                :closable="false"
        >
            <Form ref="deptFormItem" :model="deptFormItem" :rules="deptValidator" :label-width="80">
                <Row>
                    <Col span="12">
                        <FormItem label="部门名称" prop="name">
                            <Input v-model="deptFormItem.name" placeholder="请输入部门名称">
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="备注">
                            <Input v-model="deptFormItem.remarks" placeholder="请输入备注">
                            </Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                        <FormItem label="是否可用" prop="useable">
                            <Select v-model="deptFormItem.useable" placeholder="请选择">
                                <Option v-for="item in useableList" :value="item.value" :key="item.label">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="排序" prop="orderNum">
                            <Input type="text" v-model="deptFormItem.orderNum" placeholder="请输入排序">
                            </Input>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" icon="checkmark-round" @click="saveDept('deptFormItem')">保存</Button>
                <Button type="error" icon="close-round" @click="cancelSave('deptFormItem')">取消</Button>
            </div>
        </Modal>
        <Modal
                title="人员数据"
                v-model="addMember"
                ok-text="保存"
                :closable="false"
        >
            <Form ref="memberFormItem" :model="memberFormItem" :rules="memValidator" :label-width="80">
                <Row>
                    <Col span="12">
                    <FormItem label="姓名" prop="name">
                        <Input v-model="memberFormItem.name" placeholder="请输入姓名">
                        </Input>
                    </FormItem>
                    </Col>
                    <Col span="12">
                    <FormItem label="性别" prop="gender">
                        <Select v-model="memberFormItem.gender" placeholder="请选择">
                            <Option v-for="item in genderList" :value="item.value" :key="item.label">{{item.label}}</Option>
                        </Select>
                    </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                    <FormItem label="手机号" prop="mobile">
                        <Input v-model="memberFormItem.mobile" placeholder="请输入手机号">
                        </Input>
                    </FormItem>
                    </Col>
                    <Col span="12">
                    <FormItem label="邮箱" prop="email">
                        <Input type="text" v-model="memberFormItem.email" placeholder="请输入邮箱">
                        </Input>
                    </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" icon="checkmark-round" @click="saveMember('memberFormItem')">保存</Button>
                <Button type="error" icon="close-round" @click="cancelSave('memberFormItem')">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
  import { fetchGetData,fetchPostData,adminUrl} from '@/libs/fetch.js'
  import util from '@/libs/util.js'
  export default {
    name: 'deptList',
    data () {
      const orderValidator=(rule,value,callback) => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'));
        } else {
          callback();
        }
      };
      const mobileValidator=(rule,value,callback)=>{
        if(value===''){
          callback(new Error('手机号不能为空'));
        }else if(!/^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/.test(value)){
          callback(new Error('手机号格式不正确'));
        }else{
          callback();
        }
      };
      return {
        keyWord: '',
        deptData: [],
        allDeptData: [],
        selectedNode: [],
        realName: '',
        addDept: false,
        deptFormItem: {
          name: '',
          remarks: '',
          useable: '',
          orderNum: 0,
          parentId: ''
        },
        selectedNodeDetail: {
          name: '',
          remarks: '',
          useable: '',
          orderNum: 0
        },
        isEdit: false, //为true时更新
        useableList: [{
          value: 1,
          label: '是'
        },{
          value: 0,
          label: '否'
        }],
        deptValidator: {
          name: [{ required: true, message: '部门名称不能为空', trigger: 'blur'}],
          useable: [{ type: 'number', required: true, message: '是否可用不能为空', trigger: 'change'}],
          orderNum: [{ validator: orderValidator, trigger: 'blur'}]
        },
        memValidator: {
          mobile: [{ required: true, validator:mobileValidator, trigger: 'blur'}],
          name: [{ required: true, message: '姓名不能为空', trigger: 'blur'}],
          email:[
            { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
          ],
          gender: [{ required: true, message: '性别不能为空', trigger: 'change'}]
        },
        addMember: false,
        memberFormItem: {
          name: '',
          deptId: '',
          mobile: '',
          email: '',
          gender: ''
        },
        genderList: [{
          value: '1',
          label: '男'
        },{
          value: '0',
          label: '女'
        }],
        is_loading:true,
        dataCount: 0, // 初始化信息总条数
        pageSize: 10, // 每页显示多少条
        DataColumns: [
          {
            title:'编号',
            type: 'index',
            align:'center'
          },{
            title:'姓名',
            key:'name',
            align:'center'
          },{
            title:'性别',
            key:'gender',
            align:'center',
            render: (h, params) => {
              let value = params.row.gender == 1 ? '男' : '女';
              return h('div',value);
            }
          },{
            title:'手机号',
            key:'mobile',
            align:'center'
          },{
            title:'邮箱',
            key:'email',
            align:'center'
          },{
            title:'创建时间',
            key:'createTime',
            align:'center'
          },{
            title:'更新时间',
            key:'updateTime',
            align:'center'
          }],
        tableData:[],
        selectRowData:'',
      };
    },
    methods: {
      //部门树列表
      getDeptList(){
        this.$Loading.start();
        this.selectedNode = [];
        this.selectedNodeDetail = [];
        fetchGetData(adminUrl+'/admin/dept/query').then(data => {
          if (data.status == 1) {
            this.$Loading.finish();
            this.deptData = util.deepcopy(data.data);
            this.allDeptData = data.data;
          } else {
            this.$Loading.error();
          }
        });
      },
      //选中公司树节点
      handleselectchange(selectNode){
        this.selectedNode = selectNode;
        this.realName = '';
        this.tableData = [];
        this.selectRowData = '';
        //查询部门信息和人员列表
        if(this.selectedNode.length > 0){
          this.getDeptDetail(this.selectedNode[0].id);
          this.getTableList(this.selectedNode[0].id,1,this.pageSize);
        }
      },
      getDeptDetail(deptId){
        fetchGetData(adminUrl+'/admin/dept/detail/' + deptId, {}).then(data => {
          if (data.status == 1) {
            this.$Loading.finish();
            this.selectedNodeDetail = data.data;
          } else {
            this.$Loading.error();
          }
        });
      },
      //新增或修改部门
      handleAddDept(index){
        if (this.selectedNode.length > 0){
          this.addDept = true;
          if(index == 1){
            this.isEdit = false;
            this.deptFormItem.parentId = this.selectedNode[0].id;
          }else{
            this.isEdit = true;
            this.deptFormItem = util.deepcopy(this.selectedNodeDetail);
          }
        }else{
          this.$Message.error('请先选择公司或部门');
        }
      },
      //新增或修改人员信息
      handleAddMember(index){
        if(index == 1){
          if (this.selectedNode.length > 0){
            this.memberFormItem.deptId = this.selectedNode[0].id;
            this.isEdit = false;
            this.addMember = true;
          }else{
            this.$Message.error('请先选择公司或部门');
          }
        }else{
          if(this.selectRowData.id){
            this.memberFormItem.deptId = this.selectedNode[0].id;
            this.isEdit = true;
            this.addMember = true;
            this.getMemberDetail(this.selectRowData.id);
          }else{
            this.$Message.error('请选中要修改的行');
          }
        }
      },
      getMemberDetail(userId){
        fetchGetData(adminUrl+'/admin/dept/userDetail/' + userId, {}).then(data => {
          if (data.status == 1) {
            this.$Loading.finish();
            this.memberFormItem = data.data;
          } else {
            this.$Loading.error();
          }
        });
      },
      saveDept(name){
        this.$refs[name].validate((valid) => {
          if (valid) {
            let url = '/admin/dept/addDept';
            if(this.isEdit){
              url = '/admin/dept/updateDept';
            }
            fetchPostData(adminUrl+url,this.deptFormItem)
              .then(data=>{
                if(data.status==1){
                  this.cancelSave(name);
                  let _that = this;
                  this.$Notice.success({
                    title: data.message,
                    duration:2,
                    onClose:function () {
                      _that.getDeptList();
                    }
                  })
                }else{
                  this.$Notice.error({
                    title: '保存失败',
                    desc: data.message,
                    duration:0
                  });
                }
              });
          } else {
            this.$Message.error('信息输入有误!');
          }
        })
      },
      saveMember(name){
        this.$refs[name].validate((valid) => {
          if (valid) {
            let url = '/admin/dept/userAdd';
            if(this.isEdit){
              this.memberFormItem['id'] = this.selectRowData.id;
              url = '/admin/dept/userUpdate';
            }
            fetchPostData(adminUrl+url,this.memberFormItem)
              .then(data=>{
                if(data.status==1){
                  this.cancelSave(name);
                  let _that = this;
                  this.$Notice.success({
                    title: data.message,
                    duration:2,
                    onClose:function () {
                      _that.getTableList(_that.selectedNode[0].id,1,_that.pageSize);
                    }
                  })
                }else{
                  this.$Notice.error({
                    title: '保存失败',
                    desc: data.message,
                    duration:0
                  });
                }
              });
          } else {
            this.$Message.error('信息输入有误!');
          }
        })
      },
      cancelSave(name){
        this.$refs[name].resetFields();
        if(name == 'memberFormItem'){
          this.addMember = false;
        }else{
          this.addDept = false;
        }
      },
      handleDelDept(){
        if (this.selectedNode.length > 0) {
          fetchPostData(adminUrl+'/admin/dept/del/' + this.selectedNode[0].id, {}).then(data => {
            if (data.status == 1) {
              let _that = this;
              this.$Notice.success({
                title: data.message,
                duration: 2,
                onClose: function () {
                  _that.getDeptList();
                }
              })
            } else {
              this.$Message.error(data.message);
            }
          });
        } else {
          this.$Message.error('请先选中要删除的部门');
        }
      },
      handleDelMember(){
        if (this.selectRowData.id) {
          fetchPostData(adminUrl+'/admin/dept/userDel/' + this.selectRowData.id, {}).then(data => {
            if (data.status == 1) {
              let _that = this;
              this.$Notice.success({
                title: data.message,
                duration: 2,
                onClose: function () {
                  _that.getTableList(_that.selectedNode[0].id,1,_that.pageSize);
                }
              })
            } else {
              this.$Message.error(data.message);
            }
          });
        } else {
          this.$Message.error('请先选中要删除的记录');
        }
      },
      //搜索
      handleSearch(){
        if(this.selectedNode.length > 0){
          this.getTableList(this.selectedNode[0].id,1,this.pageSize);
        }
      },
      getTableList(id, pageNum, pageSize){
        this.$Loading.start();
        fetchGetData(adminUrl+'/admin/dept/userList', {
          deptId: id,
          pageNum: pageNum,
          pageSize: pageSize,
          name: this.realName
        }).then(data => {
          if (data.status == 1) {
            this.is_loading = false;
            this.$Loading.finish();
            this.tableData = data.data.rows;
          } else {
            this.is_loading = false;
            this.$Loading.error();
          }
        });
      },
      changePage(index) {
        if (this.selectedNode.length > 0) {
          this.getDeptList(this.selectedNode[0], index, this.pageSize);
        }
      },
      //选中表格的行
      handleRowChange (currentRow, oldCurrentRow) {
        this.selectRowData = currentRow;
      }
    },
    created(){
      this.getDeptList();
    }
  };
</script>